Imports System
Imports System.IO
Imports System.Net

''' <summary>
''' Methods to handle the GeoIP database from www.maxmind.com.
''' </summary>
Public Class GeoIPUtil

#Region "Private constructor"

	Private Sub New()
		' Can't create instance!
	End Sub

#End Region

#Region "Properties"

	Public Shared CountryDatabase As MemoryStream

	Private Shared CountryBegin As Long = 16776960
	Private Shared CountryName As String() = {"", "Asia/Pacific Region", "Europe", "Andorra", "United Arab Emirates", "Afghanistan", "Antigua and Barbuda", "Anguilla", "Albania", "Armenia", "Netherlands Antilles", "Angola", "Antarctica", "Argentina", "American Samoa", "Austria", "Australia", "Aruba", "Azerbaijan", "Bosnia and Herzegovina", "Barbados", "Bangladesh", "Belgium", "Burkina Faso", "Bulgaria", "Bahrain", "Burundi", "Benin", "Bermuda", "Brunei Darussalam", "Bolivia", "Brazil", "Bahamas", "Bhutan", "Bouvet Island", "Botswana", "Belarus", "Belize", "Canada", "Cocos (Keeling) Islands", "Congo, The Democratic Republic of the", "Central African Republic", "Congo", "Switzerland", "Cote D'Ivoire", "Cook Islands", "Chile", "Cameroon", "China", "Colombia", "Costa Rica", "Cuba", "Cape Verde", "Christmas Island", "Cyprus", "Czech Republic", "Germany", "Djibouti", "Denmark", "Dominica", "Dominican Republic", "Algeria", "Ecuador", "Estonia", "Egypt", "Western Sahara", "Eritrea", "Spain", "Ethiopia", "Finland", "Fiji", "Falkland Islands (Malvinas)", "Micronesia, Federated States of", "Faroe Islands", "France", "France, Metropolitan", "Gabon", "United Kingdom", "Grenada", "Georgia", "French Guiana", "Ghana", "Gibraltar", "Greenland", "Gambia", "Guinea", "Guadeloupe", "Equatorial Guinea", "Greece", "South Georgia and the South Sandwich Islands", "Guatemala", "Guam", "Guinea-Bissau", "Guyana", "Hong Kong", "Heard Island and McDonald Islands", "Honduras", "Croatia", "Haiti", "Hungary", "Indonesia", "Ireland", "Israel", "India", "British Indian Ocean Territory", "Iraq", "Iran, Islamic Republic of", "Iceland", "Italy", "Jamaica", "Jordan", "Japan", "Kenya", "Kyrgyzstan", "Cambodia", "Kiribati", "Comoros", "Saint Kitts and Nevis", "Korea, Democratic People's Republic of", "Korea, Republic of", "Kuwait", "Cayman Islands", "Kazakstan", "Lao People's Democratic Republic", "Lebanon", "Saint Lucia", "Liechtenstein", "Sri Lanka", "Liberia", "Lesotho", "Lithuania", "Luxembourg", "Latvia", "Libyan Arab Jamahiriya", "Morocco", "Monaco", "Moldova, Republic of", "Madagascar", "Marshall Islands", "Macedonia, the Former Yugoslav Republic of", "Mali", "Myanmar", "Mongolia", "Macao", "Northern Mariana Islands", "Martinique", "Mauritania", "Montserrat", "Malta", "Mauritius", "Maldives", "Malawi", "Mexico", "Malaysia", "Mozambique", "Namibia", "New Caledonia", "Niger", "Norfolk Island", "Nigeria", "Nicaragua", "Netherlands", "Norway", "Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama", "Peru", "French Polynesia", "Papua New Guinea", "Philippines", "Pakistan", "Poland", "Saint Pierre and Miquelon", "Pitcairn", "Puerto Rico", "Palestinian Territory, Occupied", "Portugal", "Palau", "Paraguay", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saudi Arabia", "Solomon Islands", "Seychelles", "Sudan", "Sweden", "Singapore", "Saint Helena", "Slovenia", "Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino", "Senegal", "Somalia", "Suriname", "Sao Tome and Principe", "El Salvador", "Syrian Arab Republic", "Swaziland", "Turks and Caicos Islands", "Chad", "French Southern Territories", "Togo", "Thailand", "Tajikistan", "Tokelau", "Turkmenistan", "Tunisia", "Tonga", "Timor-Leste", "Turkey", "Trinidad and Tobago", "Tuvalu", "Taiwan, Province of China", "Tanzania, United Republic of", "Ukraine", "Uganda", "United States Minor Outlying Islands", "United States", "Uruguay", "Uzbekistan", "Holy See (Vatican City State)", "Saint Vincent and the Grenadines", "Venezuela", "Virgin Islands, British", "Virgin Islands, U.S.", "Vietnam", "Vanuatu", "Wallis and Futuna", "Samoa", "Yemen", "Mayotte", "Yugoslavia", "South Africa", "Zambia", "Montenegro", "Zimbabwe", "Anonymous Proxy", "Satellite Provider", "Other", "Aland Islands", "Guernsey", "Isle of Man", "Jersey", "Saint Barthelemy", "Saint Martin"}
	Private Shared CountryCode As String() = {"", "AP", "EU", "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BM", "BN", "BO", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU", "CV", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "FX", "GA", "GB", "GD", "GE", "GF", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IN", "IO", "IQ", "IR", "IS", "IT", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "ST", "SV", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TM", "TN", "TO", "TL", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "RS", "ZA", "ZM", "ME", "ZW", "A1", "A2", "O1", "AX", "GG", "IM", "JE", "BL", "MF"}

#End Region

#Region "Load database"

	''' <summary>
	''' Load the country database from the specified path.
	''' </summary>
	Public Shared Sub LoadCountryDatabase(ByVal path As String)

		Dim fs As New FileStream(path, FileMode.Open, FileAccess.Read)
		Dim bytes(256) As Byte

		CountryDatabase = New MemoryStream()

		While fs.Read(bytes, 0, bytes.Length) <> 0
			CountryDatabase.Write(bytes, 0, bytes.Length)
		End While

		fs.Dispose()

	End Sub

	''' <summary>
	''' Gets the specified file and returns the representing memory stream.
	''' </summary>
	''' <returns>MemoryStream object for the file.</returns>
	Public Shared Function FileToMemory(ByVal path As String) As MemoryStream

		Dim fs As New FileStream(path, FileMode.Open, FileAccess.Read)
		Dim ms As New MemoryStream()
		Dim bytes(256) As Byte

		While fs.Read(bytes, 0, bytes.Length) <> 0
			ms.Write(bytes, 0, bytes.Length)
		End While

		fs.Dispose()

		Return ms

	End Function

#End Region

#Region "Lookup country"

	''' <summary>
	''' Gets the country code for the specified IPAddress object.
	''' </summary>
	''' <returns>Standard country code (2 letters), empty string if not found.</returns>
	Public Shared Function LookupCountryCode(ByVal ip As IPAddress) As String

		Return CountryCode(CInt(SeekCountry(0, ConvertIPAddressToNumber(ip), 31)))

	End Function

	''' <summary>
	''' Gets the country code for the specified IP address.
	''' </summary>
	''' <returns>Standard country code (2 letters), empty string if not found.</returns>
	Public Shared Function LookupCountryCode(ByVal ip As String) As String

		Dim address As IPAddress

		Try

			address = IPAddress.Parse(ip)

		Catch ex As FormatException

			Return String.Empty

		End Try

		Return LookupCountryCode(address)

	End Function

	''' <summary>
	''' Gets the country name for the specified IPAddress object.
	''' </summary>
	''' <returns>Standard country name, empty string if not found.</returns>
	Public Shared Function LookupCountryName(ByVal ip As IPAddress) As String

		Return CountryName(CInt(SeekCountry(0, ConvertIPAddressToNumber(ip), 31)))

	End Function

	''' <summary>
	''' Gets the country name for the specified IP address.
	''' </summary>
	''' <returns>Standard country name, empty string if not found.</returns>
	Public Shared Function LookupCountryName(ByVal ip As String) As String

		Dim address As IPAddress

		Try

			address = IPAddress.Parse(ip)

		Catch e As FormatException

			Return String.Empty

		End Try

		Return LookupCountryName(address)

	End Function

#End Region

#Region "Helper methods"

	Private Shared Function SeekCountry(ByVal StartOffset As Long, ByVal IPNumber As Long, ByVal SearchDepth As Integer) As Long

		Dim buffer(6) As Byte
		Dim x(2) As Long
		Dim i As Integer

		If SearchDepth = 0 Then

			Return 0

		End If

		Try
			CountryDatabase.Seek(6 * StartOffset, 0)
			CountryDatabase.Read(buffer, 0, 6)
		Catch
		End Try

		For i = 0 To 1

			x(i) = 0

			Dim j As Integer

			For j = 0 To 2

				Dim part As Integer = buffer((i * 3 + j))

				If part < 0 Then
					part += 256
				End If

				x(i) += vbShiftLeft(part, (j * 8))

			Next j

		Next i

		If (IPNumber And vbShiftLeft(1, SearchDepth)) > 0 Then

			If x(1) >= CountryBegin Then

				Return x(1) - CountryBegin

			End If

			Return SeekCountry(x(1), IPNumber, SearchDepth - 1)

		Else

			If x(0) >= CountryBegin Then

				Return x(0) - CountryBegin

			End If

			Return SeekCountry(x(0), IPNumber, SearchDepth - 1)

		End If

	End Function

	Private Shared Function ConvertIPAddressToNumber(ByVal ip As IPAddress) As Long

		Dim address() As String = ip.ToString().Split(".".ToCharArray())

		If address.Length = 4 Then
			Return Convert.ToInt64(16777216 * Convert.ToInt64(address(0)) + 65536 * Convert.ToInt64(address(1)) + 256 * Convert.ToInt64(address(2)) + Convert.ToInt64(address(3)))
		Else
			Return 0
		End If

	End Function

	Private Shared Function ConvertIPNumberToAddress(ByVal ip As Long) As String

		Dim ip1 As String = (Convert.ToInt32(ip / 16777216) Mod 256).ToString()
		Dim ip2 As String = (Convert.ToInt32(ip / 65536) Mod 256).ToString()
		Dim ip3 As String = (Convert.ToInt32(ip / 256) Mod 256).ToString()
		Dim ip4 As String = (Convert.ToInt32(ip) Mod 256).ToString()

		Return ip1 & "." & ip2 & "." & ip3 & "." & ip4

	End Function

	Private Shared Function vbShiftLeft(ByVal Value As Long, ByVal Count As Integer) As Long

		Dim left As Long = Value
		Dim i As Integer

		For i = 1 To Count
			left = left * 2
		Next

		Return left

	End Function

	Private Shared Function vbShiftRight(ByVal Value As Long, ByVal Count As Integer) As Long

		Dim right As Long = Value
		Dim i As Integer

		For i = 1 To Count
			right = right \ 2
		Next

		Return right

	End Function

#End Region

End Class